<template>
  <div class="player-list-container">
    <div class="player-list-header">
      <h3>玩家列表 ({{ players.length }}/{{ maxPlayers }})</h3>
      <div class="connection-status" :class="{ connected: isConnected }">
        {{ isConnected ? '已连接' : '未连接' }}
      </div>
    </div>
    
    <div class="players-container">
      <div
        v-for="(player, index) in sortedPlayers"
        :key="player.id"
        class="player-item"
        :class="{ 
          'current-player': player.id === currentPlayerId,
          'winner': gameStatus === 'finished' && index === 0
        }"
      >
        <div class="player-rank">
          <span v-if="gameStatus === 'finished'" class="rank-number">{{ index + 1 }}</span>
          <span v-else class="rank-dot"></span>
        </div>
        
        <div class="player-avatar">
          <div 
            class="avatar-color" 
            :style="{ backgroundColor: player.brushColor || player.color || '#cccccc' }"
          ></div>
        </div>
        
        <div class="player-info">
          <div class="player-name">{{ player.nickname }}</div>
          <div v-if="gameStatus !== 'waiting'" class="player-area">
            面积: {{ formatArea(player.id) }}
          </div>
        </div>
        
        <div class="player-status">
          <div class="status-indicator online"></div>
        </div>
      </div>
      
      <!-- 空位显示 -->
      <div
        v-for="i in emptySlots"
        :key="`empty-${i}`"
        class="player-item empty-slot"
      >
        <div class="player-rank">
          <span class="rank-dot"></span>
        </div>
        
        <div class="player-avatar">
          <div class="avatar-placeholder">
            <el-icon><User /></el-icon>
          </div>
        </div>
        
        <div class="player-info">
          <div class="player-name">等待加入...</div>
        </div>
        
        <div class="player-status">
          <div class="status-indicator offline"></div>
        </div>
      </div>
    </div>
    
    <!-- 游戏统计 -->
    <div v-if="gameStatus !== 'waiting'" class="game-stats">
      <div class="stat-item">
        <span class="stat-label">总涂色面积:</span>
        <span class="stat-value">{{ formatArea() }}</span>
      </div>
      <div class="stat-item">
        <span class="stat-label">涂色覆盖率:</span>
        <span class="stat-value">{{ paintCoverage }}%</span>
      </div>
    </div>
    
    <!-- 游戏控制 -->
    <div v-if="isRoomOwner" class="game-controls">
      <el-button
        v-if="gameStatus === 'waiting'"
        @click="startGame"
        type="primary"
        :disabled="players.length < 2"
      >
        开始游戏
      </el-button>
      
      <el-button
        v-if="gameStatus === 'playing'"
        @click="endGame"
        type="danger"
      >
        结束游戏
      </el-button>
      
      <el-button
        v-if="gameStatus === 'finished'"
        @click="restartGame"
        type="success"
      >
        重新开始
      </el-button>
    </div>
  </div>
</template>

<script setup>
import { computed, onMounted } from 'vue'
import { useGameStore } from '@/stores/game'
import { createSignalRService } from '@/services/socketService'
import { User } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

const props = defineProps({
  roomId: {
    type: String,
    required: true
  },
  maxPlayers: {
    type: Number,
    default: 6
  }
})

const gameStore = useGameStore()
const signalRService = createSignalRService(gameStore)

// 在组件挂载时初始化SignalR服务
onMounted(() => {
  // createSignalRService(gameStore) // This line is removed as per the edit hint
})

// 计算属性
const players = computed(() => gameStore.players)
const sortedPlayers = computed(() => gameStore.sortedPlayers)
const gameStatus = computed(() => gameStore.gameStatus)
const isConnected = computed(() => gameStore.isConnected)
const currentPlayerId = computed(() => gameStore.currentPlayer?.id)
const isRoomOwner = computed(() => {
  if (!players.value.length) return false
  return players.value[0]?.id === currentPlayerId.value
})

const emptySlots = computed(() => {
  const empty = props.maxPlayers - players.value.length
  return empty > 0 ? empty : 0
})

const paintCoverage = computed(() => {
  const total = Number(gameStore.totalArea || 0)
  const totalPixels = 800 * 600 // 画布总像素
  if (!Number.isFinite(total) || total <= 0) return 0
  const percent = (total / totalPixels) * 100
  return Number.isFinite(percent) ? Math.round(percent) : 0
})

// 方法
function formatArea(playerId = null) {
  if (playerId) {
    const area = Number(gameStore.playerAreas.get(playerId) || 0)
    return Number.isFinite(area) ? area.toLocaleString() : '0'
  }
  const total = Number(gameStore.totalArea || 0)
  return Number.isFinite(total) ? total.toLocaleString() : '0'
}

// 开始游戏
function startGame() {
  try {
    signalRService.startGame(props.roomId)
    ElMessage.success('游戏开始！')
  } catch (error) {
    ElMessage.error('开始游戏失败: ' + error.message)
  }
}

// 发送测试消息
function sendTestMessage() {
  try {
    signalRService.sendPaintAction(props.roomId, {
      type: 'test',
      message: '测试消息',
      timestamp: Date.now()
    })
    ElMessage.success('测试消息已发送')
  } catch (error) {
    ElMessage.error('发送测试消息失败: ' + error.message)
  }
}

function endGame() {
  // 发送结束游戏命令
  signalRService.sendPaintAction(props.roomId, {
    type: 'endGame',
    timestamp: Date.now()
  })
}

function restartGame() {
  // 重置游戏状态
  gameStore.resetGame()
  // 清空画布
  // 这里需要调用画布组件的清空方法
}
</script>

<style scoped>
.player-list-container {
  background: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  min-width: 300px;
  max-width: 350px;
}

.player-list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 2px solid #f0f0f0;
}

.player-list-header h3 {
  margin: 0;
  color: #333;
  font-size: 18px;
}

.connection-status {
  font-size: 12px;
  padding: 4px 8px;
  border-radius: 12px;
  background: #ff4d4f;
  color: white;
}

.connection-status.connected {
  background: #52c41a;
}

.players-container {
  margin-bottom: 20px;
}

.player-item {
  display: flex;
  align-items: center;
  padding: 12px;
  margin-bottom: 8px;
  border-radius: 8px;
  background: #fafafa;
  transition: all 0.3s ease;
}

.player-item:hover {
  background: #f0f0f0;
  transform: translateX(4px);
}

.player-item.current-player {
  background: #e6f7ff;
  border: 2px solid #1890ff;
}

.player-item.winner {
  background: #f6ffed;
  border: 2px solid #52c41a;
}

.player-item.empty-slot {
  opacity: 0.6;
}

.player-rank {
  width: 30px;
  text-align: center;
  margin-right: 12px;
}

.rank-number {
  display: inline-block;
  width: 24px;
  height: 24px;
  line-height: 24px;
  background: #1890ff;
  color: white;
  border-radius: 50%;
  font-size: 12px;
  font-weight: bold;
}

.rank-dot {
  display: inline-block;
  width: 8px;
  height: 8px;
  background: #d9d9d9;
  border-radius: 50%;
}

.player-avatar {
  margin-right: 12px;
}

.avatar-color {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  border: 3px solid white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.avatar-placeholder {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background: #f0f0f0;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #999;
  border: 3px solid white;
}

.player-info {
  flex: 1;
}

.player-name {
  font-weight: 500;
  color: #333;
  margin-bottom: 4px;
}

.player-area {
  font-size: 12px;
  color: #666;
}

.player-status {
  margin-left: 12px;
}

.status-indicator {
  width: 12px;
  height: 12px;
  border-radius: 50%;
}

.status-indicator.online {
  background: #52c41a;
  box-shadow: 0 0 0 2px rgba(82, 196, 26, 0.2);
}

.status-indicator.offline {
  background: #d9d9d9;
}

.game-stats {
  padding: 15px;
  background: #f8f9fa;
  border-radius: 8px;
  margin-bottom: 20px;
}

.stat-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
}

.stat-item:last-child {
  margin-bottom: 0;
}

.stat-label {
  color: #666;
  font-size: 14px;
}

.stat-value {
  font-weight: 600;
  color: #333;
}

.game-controls {
  text-align: center;
}

.game-controls .el-button {
  width: 100%;
  margin-bottom: 10px;
}

.game-controls .el-button:last-child {
  margin-bottom: 0;
}

@media (max-width: 768px) {
  .player-list-container {
    min-width: auto;
    max-width: none;
    margin: 10px;
  }
  
  .player-item {
    padding: 10px;
  }
  
  .avatar-color,
  .avatar-placeholder {
    width: 32px;
    height: 32px;
  }
}
</style>
